namespace NBody.Analysis
{
    using System;
    using System.IO;
    using DataFile;
     
    public class Image
    {
        public enum ViewerAxis { X, Y, Z };
        
        private int n_grid;
        private Table data;
        private ViewerAxis axis;
        
        public Image()
        {
            this.n_grid = 300;
            this.axis = ViewerAxis.Z;
            this.data = null;
        }
        
        public int GridPoints
        {
            set { n_grid = value; }
        }
        
        public ViewerAxis Axis
        {
            set { axis = value; }
        }
                
        public void Create(NBodySystem system)
        {
            Console.Error.WriteLine("Creating {0}x{0} image of system, looking down {1} axis", n_grid, axis);
            
            data = new Table(n_grid * n_grid, 3);
            
            // create a box around system
            double l = system.Rmax;
            double delta = 2.0 * l / n_grid;
            
            for (int i = 0; i < system.NumParts; i++)
            {
                double x, y;
                if (axis == ViewerAxis.X)
                {
                    x = system[i].Y + l;
                    y = system[i].Z + l;
                }
                else if (axis == ViewerAxis.Y)
                {
                    x = system[i].Z + l;
                    y = system[i].X + l;
                }
                else // if (axis == ViewerAxis.Z)
                {
                    x = system[i].X + l;
                    y = system[i].Y + l;
                }
                int pos_x = (int)(x / delta);
                int pos_y = (int)(y / delta);
                
                // make these backwards so wip shows
                // image correctly
                data[pos_x + n_grid * pos_y, 0] = pos_x;
                data[pos_x + n_grid * pos_y, 1] = pos_y;
                data[pos_x + n_grid * pos_y, 2] += 1.0;
            }
        }
        
        public void WriteBasic(string file)
        {
            Console.Error.WriteLine("Writing image to {0} as BASIC format", file);
            
            using (BinaryWriter bw = new BinaryWriter(File.Open(file, FileMode.Create)))
            {
                for (int i = 0; i < data.Length; i++)
                {
                    bw.Write(data[i, 2]);
                }
            }
        }
    }
}
            
        
